#include "acceptor.h"
#include "common.h"
#include "event_loop.h"
#include "tcp_server.h"
#include "tcp_connection.h"

char rot13_char(char c)
{
    if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
        return c + 13;
    else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
        return c - 13;
    else
        return c;
}

int on_connection_completed(struct tcp_connection *conn)
{
    printf("connection completed\n");
    return 0;
}

int on_message(struct buffer *input, struct tcp_connection *conn)
{
    printf("get message from tcp connection %s\n", conn->name);
    printf("%s", input->data);

    struct buffer *output = buffer_new();
    int size = buffer_readable_size(input);
    for (int i = 0; i < size; i++)
    {
        buffer_append_char(output, rot13_char(buffer_read_char(input)));
    }
    tcp_connection_send_buffer(conn, output);
    return 0;
}

int on_write_completed(struct tcp_connection *conn)
{
    printf("write completed\n");
    return 0;
}

int on_connection_closed(struct tcp_connection *conn)
{
    printf("connection closed\n");
    return 0;
}

int main(int argc, char const *argv[])
{
    struct event_loop *eloop = event_loop_init();
    struct acceptor *acceptor = acceptor_init(3000);
    // thread_num 为 0 的情况下，只有 acceptor 没有 sub-reactor
    struct TCPServer *server = tcp_server_init(eloop,
                                               acceptor,
                                               on_connection_completed,
                                               on_message,
                                               on_write_completed,
                                               on_connection_closed,
                                               0);
    tcp_server_start(server);
    event_loop_run(eloop);
    return 0;
}
